/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * frmFinalizaTurma.java
 *
 * Created on Jun 21, 2010, 4:49:22 AM
 */

package br.edu.sistemaacademico;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;

import br.edu.sistemaacademico.Decorator.ConcretDecorator;
import br.edu.sistemaacademico.adapter.IMenuCadastro;
import br.edu.sistemaacademico.facade.DataFacade;
import br.edu.sistemaacademico.pojo.Historico;
import br.edu.sistemaacademico.pojo.Matricula;
import br.edu.sistemaacademico.pojo.Turma;
import br.edu.sistemaacademico.state.StateHandler;
import client.ClientCommand;

/**
 *
 * @author baron
 */
public class frmFinalizaTurma extends IMenuCadastro {

	Turma turma;
	StateHandler stateAlterarExcuir = new StateHandler(false);
	 public List<Object> campos = new ArrayList<Object>();
	    private List<Object> valores = new ArrayList<Object>();
	    private List<Object> tamanho = new ArrayList<Object>();
	    TabelaModelo tabModel;
	    List<Historico> extra;
	    ConcretDecorator cc = null;
	    Matricula matricula;
	    Historico historico;
	    
    public frmFinalizaTurma(Turma turma) {
        initComponents();
        tamanho.add(70);
        campos.add("matricula");
        campos.add("Aluno");
        campos.add("Faltas");
        campos.add("Nota");
        campos.add("situacao");
        
        this.turma = turma;
        tabModel = new TabelaModelo(campos, tamanho, jTable1);
        if (cc==null)
            cc = new ConcretDecorator(this);
        ListSelectionModel listModel = jTable1.getSelectionModel();
        listModel.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        listModel.addListSelectionListener(list);
        jTable1.getModel().addTableModelListener(tablist);
        setButtons();
        setStateAlteraExcuir();
        atualizaMatricula();
        cc.setVisible(true);
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.setName("jTable1");
        jScrollPane1.setViewportView(jTable1);

        jButton1.setText("Finalizar");
        jButton1.setName("jButton1");

        jButton2.setText("Limpar");
        jButton2.setName("jButton2"); // NOI18N

        jButton3.setText("Cancelar");
        jButton3.setName("jButton3"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jButton1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 525, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 188, Short.MAX_VALUE)
                        .addComponent(jButton2)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1))
        );
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    
	ListSelectionListener list = new ListSelectionListener() {
		
		@Override
		public void valueChanged(ListSelectionEvent e) {
			try{
				if(jTable1.getSelectedRow()>=0){
				stateAlterarExcuir.change(true);
			historico = getSelectedHistorico(Long.parseLong(jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString()));
				}
			}catch(ArrayIndexOutOfBoundsException ea){
				historico = null;
				stateAlterarExcuir.change(false);
			}
		}
	};
	
	TableModelListener tablist = new TableModelListener() {
		
		@Override
		public void tableChanged(TableModelEvent e) {
			if(e.getType()== e.UPDATE)
				if(jTable1.getSelectedRow()>=0){
			extra.get(jTable1.getSelectedRow()).setFaltas(Integer.parseInt(jTable1.getValueAt(jTable1.getSelectedRow(), 2).toString()));
			extra.get(jTable1.getSelectedRow()).setMedia(Float.parseFloat(jTable1.getValueAt(jTable1.getSelectedRow(), 3).toString()));
			
			//jTable1.updateUI();
			}
			//jTable1.updateUI();
			//if(jTable1.getSelectedRow()>=0)
			//	System.out.println(extra.get(jTable1.getSelectedRow()).getMatricula().getId()+" faltas: "+extra.get(jTable1.getSelectedRow()).getFaltas());
		}
	};
	
	
	public Historico getSelectedHistorico(Long codigo){
		return (Historico) ClientCommand.carregaObjeto("HistoricoService", "matricula="+codigo, "");
	}
	 public void atualizaMatricula(){
			((DefaultTableModel) jTable1.getModel()).setNumRows(0);
			jTable1.updateUI();
			extra = (List) ClientCommand.carregar("HistoricoService","turma="+turma.getId(),"");
			DataFacade entrada = new DataFacade();   
	    	for(int i = 0; i < extra.size();i++ ){
	    		valores = new LinkedList<Object>();
	    		valores.add(extra.get(i).getMatricula().getId());
	    		valores.add(extra.get(i).getMatricula().getAluno().getNome());
	    		valores.add(extra.get(i).getFaltas());
	    		valores.add(extra.get(i).getMedia());
	    		valores.add(extra.get(i).getSituacao());
	    		tabModel.setValores(valores);
	    		valores.clear();
	    		valores.removeAll(extra);
	    	}
	    }
	 
	 public void finalizar(){
		 Historico hist = new Historico();
		 //jTable1.getRowCount()
		 for(int i = 0; i< extra.size();i++){
			 ClientCommand.alterar("HistoricoService",(Historico)extra.get(i));			
		 }
		 atualizaMatricula();
	 }

	 public void setButtons(){
		 jButton1.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				finalizar();
			}
		});
	 }
	    public void setStateAlteraExcuir(){
	    	stateAlterarExcuir.addComponent(jButton1);

	    }
	    public void limpaFields(){
 	    }

 	    
 		@Override
 		public void menuExemplo(JMenuItem item) {
 			// TODO Auto-generated method stub
 			
 		}

 		@Override
 		public void menuFechar(JMenuItem item) {
 			cc.dispose();		
 		}

 		@Override
 		public void menuLimpa(JMenuItem item) {
 			limpaFields();		
 		}

 		@Override
 		public void menuManual(JMenuItem item) {
 			// TODO Auto-generated method stub		
 		}

 		@Override
 		public void menuMementor(JMenuItem item) {
 			// TODO Auto-generated method stub		
 		}

 		@Override
 		public void menuOperacao(JMenuItem item) {
 			item.setText("Fechar Turma");
 			finalizar();
 		}

 		@Override
 		public void menuSobre(JMenuItem item) {
 			// TODO Auto-generated method stub
 			
 		}
 	  
 
}
